package com.zzstm.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzstm.eduservice.entity.EduSubject;
import com.zzstm.eduservice.entity.excel.SubjectData;
import com.zzstm.eduservice.entity.subject.OneSubject;
import com.zzstm.eduservice.entity.subject.TwoSubject;
import com.zzstm.eduservice.listener.SubjectExcelListener;
import com.zzstm.eduservice.mapper.EduSubjectMapper;
import com.zzstm.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-10-28
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //课程分类列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //1，查询一级分类
        QueryWrapper<EduSubject> oneSubjectQueryWrapper = new QueryWrapper<>();
        oneSubjectQueryWrapper.eq("parent_id","0");
        List<EduSubject> oneSubjects = baseMapper.selectList(oneSubjectQueryWrapper);
        //2.查询二级分类
        QueryWrapper<EduSubject> twoSubjectQueryWrapper = new QueryWrapper<>();
        twoSubjectQueryWrapper.ne("parent_id","0");
        List<EduSubject> twoSubjects = baseMapper.selectList(twoSubjectQueryWrapper);
        //3。封装一级分类
        List<OneSubject> oneSubjectList = new ArrayList<>();
        for(EduSubject e : oneSubjects){
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(e,oneSubject);

            //4.封装二级分类
            List<TwoSubject> list = new ArrayList<>();
            for (EduSubject ee : twoSubjects){
                if (ee.getParentId().equals(e.getId())){
                    TwoSubject two = new TwoSubject();
                    BeanUtils.copyProperties(ee,two);
                    list.add(two);
                }
            }
            oneSubject.setChildren(list);
            oneSubjectList.add(oneSubject);
        }

        return oneSubjectList;
    }
}
